<template>
  <div class="login">
    <el-row>
      <!--左侧图片 -->
      <el-col :span="10" v-show="isShowLogo">
        <div class="login_img"></div>
      </el-col>
      <!-- 右侧 -->
      <el-col :span="isShowLogo ? 14 : 24">
        <div class="login_img bg_img login_right">
          <div class="language_dropdown">
            <switchLang></switchLang>
          </div>

          <div
            class="logo"
            :style="{
              'background-image': 'url(' + require('@/assets/img/login/' + $config.logoBgUrl) + ')',
              'margin-left': $config.logoBg_left,
            }"
          ></div>
          <!-- 机构输入框 -->
          <div class="organization-box">
            <div class="organization">
              <!-- 验证码登录 邮箱登录 -->
              <div class="organization_title">
                <div class="organization_title_wordage">
                  {{ $t('login.huanyin') }}
                </div>
                <!-- 登录方式 -->
                <div class="organization_title_way">
                  <div class="way_item activeClass">{{ $t('login.login3') }}</div>
                  <!-- <div
                    v-for="(item, i) in nameList"
                    :key="i"
                    :class="['way_item', i == activeIndex ? 'activeClass' : '']"
                    style="cursor: pointer"
                    @click="activeClick(i)"
                  >
                    {{ item }}
                  </div> -->
                </div>
              </div>
              <!-- 输入框 和登录-->
              <div class="organization_form">
                <el-form ref="emailForm" :model="emailForm" :rules="emailrules">
                  <!-- 邮箱登录 -->
                  <div v-if="activeIndex == 0">
                    <el-form-item prop="email">
                      <div class="phone_box" :class="['phone_box', getBorder]">
                        <div
                          class="ease_animation"
                          :style="{ width: isShowAreaCode ? '90px' : '0px' }"
                        >
                          <el-select v-model="phoneCode" slot="prepend" style="width: 90px">
                            <el-option
                              :label="item.paramValue"
                              :value="item.id"
                              v-for="(item, index) in phoneCodeList"
                              :key="index"
                            ></el-option>
                          </el-select>
                        </div>
                        <el-input
                          v-model="emailForm.email"
                          :placeholder="$t('patient.huanzhe28')"
                          @blur="emailBlur"
                          @focus="emailFocus"
                          @input="emailChange"
                          maxlength="100"
                        >
                          <!-- <span slot="prefix" class="el-input__icon">
                          <svg aria-hidden="true" class="icon-svg" style="margin-bottom: 6px">
                            <use xlink:href="#icon-user" />
                          </svg>
                        </span> -->
                        </el-input>
                      </div>
                    </el-form-item>
                    <el-form-item class="formItem f-item" prop="password" tem>
                      <el-input
                        v-model="emailForm.password"
                        :placeholder="$t('login.passwordtext')"
                        :type="mima1 ? 'text' : 'password'"
                        style="width: 346px"
                        maxlength="100"
                      >
                      </el-input>
                      <div class="yanjin" @click="mima1 = !mima1">
                        <img v-if="!mima1" alt src="@/assets/img/yj-bi.png" />
                        <img v-else alt src="@/assets/img/yj-kai.png" />
                      </div>
                    </el-form-item>
                    <!-- 记住密码 忘记密码 -->
                    <div class="operation" style="margin-bottom: 10px">
                      <el-checkbox v-model="passwordIscChecked" @change="pwdCheckChange">{{
                        $t('login.jizhumima')
                      }}</el-checkbox>
                      <div style="cursor: pointer" @click="resetPasswordsClick()">
                        {{ $t('login.wangjimima') }}
                      </div>
                    </div>
                  </div>
                  <div class="register" style="cursor: pointer" @click="registerPush">
                    {{ $t('login.meizhanghao') }} ?
                    <span>{{ $t('login.zhuche') }}</span>
                  </div>
                </el-form>
                <div class="organization_btn" @click="loginTarget">
                  {{ $t('login.denglu') }}
                </div>
              </div>
              <!-- 用户协议和微信登录 -->
              <div class="organization_else">
                <div class="organization_agreement" style="cursor: pointer">
                  <el-checkbox v-model="checked" />
                  <div style="margin-left: 7px" @click="checked = !checked">
                    {{ $t('login.tongyi') }}
                    <span style="color: #003e67" @click.stop="toXieyi">{{
                      $t('login.xieyi')
                    }}</span>
                  </div>
                </div>

                <!-- <div class="text">其他登录</div>
              <div @click="weChatLogin()">
                <img src="@/assets/img/login/weixin.png" alt>
              </div>-->
              </div>
            </div>
          </div>
          <div class="domin-info">
            <div
              class="domin-info-left"
              :style="[
                { position: 'relative' },
                { right: `${!$config.showCompany ? '90px' : '0px'} ` },
              ]"
            >
              <span>{{ $t('login.beian') }}</span>
              <span v-show="$config.showCompany">{{ $t('login.company') }}</span>
              <a href="https://beian.miit.gov.cn/#/Integrated/index">
                {{ $config.recordNumber }}
              </a>
              <span>{{ $t('login.currentVersion') }}:{{ currentVersion }}</span>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    <!-- //重置密码 -->
    <resetPasswords ref="resetPasswords" />
    <!-- 微信登录 -->
    <qrCode ref="qrCode" />
  </div>
</template>

<script>
import qrCode from '@/components/weChatCode/index'; // 微信登录二维码组件
import resetPasswords from '@/components/resetPasswords/index'; // 重置密码组件
import switchLang from '@/components/lang/index'; // 全局切换语言组件
import Cookies from 'js-cookie';
import { isEmail, isMobile } from '@/utils/validate';

const Base64 = require('js-base64').Base64;
import { messages } from '@/i18n';
import langs from '@/i18n/langs';
export default {
  components: {
    qrCode,
    resetPasswords,
    switchLang,
  },
  data() {
    const validateEmail = (rule, value, callback) => {
      if (value === '') {
        this.phoneLegal = false;
        callback(new Error(this.$t('login.login4')));
      } else {
        if (value.includes('@')) {
          // 是邮箱
          if (!isEmail(this.emailForm.email)) {
            this.phoneLegal = false;
            callback(new Error(this.$t('login.mima13')));
          } else {
            this.phoneLegal = true;
            callback();
          }
        } else {
          if (!isMobile(this.emailForm.email)) {
            this.phoneLegal = false;
            callback(new Error(this.$t('zhuce.zhuce18')));
          } else {
            this.phoneLegal = true;
            callback();
          }
        }
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('login.mima5')));
      } else {
        callback();
      }
    };
    return {
      // 手机号输入框是否点击过
      isClick: false,
      // 定义变量确定是否聚焦
      isFocus: false,
      // 手机号或者邮箱是否合法
      phoneLegal: true,
      // 定义区号是否出现
      isShowAreaCode: false,
      phoneCodeList: [],
      phoneCode: '85',
      // nameList: [this.$t("login.youxiang"), this.$t("login.yanzhengma")],
      // nameList: this.nameList,
      activeIndex: 0, // "0验证码登录", "1邮箱登录"切换索引
      checked: true, // 同意用户协议

      // 邮箱登录 root@renren.io
      emailForm: {
        email: '',
        password: '',
      },
      emailrules: {
        email: [
          {
            validator: validateEmail,
            trigger: 'blur',
          },
        ],
        password: [
          {
            validator: validatePassword,
            trigger: 'blur',
          },
        ],
      },
      // resetPasswordDialogVisible: false, //重置密码弹窗
      // WeChatDialogVisible: false, //
      dataRule: {}, // 校验规则
      // buttonName: this.$t('login.hqyanzhengma'),
      countdown: '',
      count: 60,
      isShow: false,
      passwordIscChecked: false, // 记住密码

      mima1: false,
      // 当前版本号
      currentVersion: '',
      // 控制左边logo的显示
      isShowLogo: true,
      // 是否展示忘记密码弹框
      isShowForgetPop: false,
    };
  },
  created() {
    let isRemember = window.localStorage.getItem('isRemember');

    if (isRemember === 'true') {
      this.passwordIscChecked = true;
    } else if (isRemember === 'false') {
      this.passwordIscChecked = false;
    }
    // 获取当前版本号
    this.getCurrentVersionData();
    // 获取手机号区号数据
    this.getPhoneArea();
  },
  computed: {
    nameList: function () {
      return [this.$t('login.youxiang')];
    },
    buttonName: function () {
      return this.$t('login.hqyanzhengma');
    },
    // 获取自定义输入框盒子的边框颜色
    getBorder: function () {
      let className = '';
      if (this.isClick) {
        if (this.isFocus) {
          if (this.phoneLegal) {
            className = 'curr_phone_box';
          } else {
            className = 'red_phone_box';
          }
        } else {
          if (this.phoneLegal) {
            className = 'curr_phone_box';
          } else {
            className = 'red_phone_box';
          }
        }
      }

      return className;
    },
  },
  mounted() {
    window.onresize = () => {
      let width = document.documentElement.clientWidth;

      if (width <= 1000) {
        this.isShowLogo = false;
      } else {
        this.isShowLogo = true;
      }
    };
  },
  methods: {
    getPhoneArea() {
      this.$http
        .get('/sys/params/page?page=1&limit=9999&paramCode=phoneNumber&paramType=1')
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.phoneCodeList = res.data.list;
          }
        })
        .catch((err) => {
          console.log('err', err);
        });
    },
    pwdCheckChange(value) {
      localStorage.setItem('isRemember', value);
    },
    getCurrentVersionData() {
      this.$http
        .post('/versionIteration/getVersionInfo')
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.currentVersion = res.data.versionNumber;
          }
        })
        .catch((err) => {
          console.log('err', err);
        });
    },
    activeClick(i) {
      this.activeIndex = i;
    },
    emailBlur(val) {
      this.isFocus = false;
      if (val.target.value && localStorage.getItem('email') == val.target.value) {
        this.emailForm.password = Base64.decode(localStorage.getItem('password')); // base64解密
      }
    },
    emailFocus() {
      this.isClick = true;
      this.isFocus = true;
    },
    emailChange() {
      
      if (this.emailForm.email.length >= 4) {
        if (!this.emailForm.email.includes('@')) {
          this.isShowAreaCode = true;
        }else {
          this.isShowAreaCode = false;
        }


      } else {
        this.isShowAreaCode = false;
      }
    },

    // 微信登录弹窗显示
    weChatLogin() {
      this.$refs.qrCode.dialogShow = true;
    },
    // 忘记密码弹窗显示
    resetPasswordsClick() {
      this.$refs.resetPasswords.dialogShow = true;
      this.$refs.resetPasswords.isCountdown = false;
    },
    // 注册跳转
    registerPush() {
      // this.$router.push('/selectionregister')
      this.$router.push('/register');
    },
    toXieyi() {
      this.openWindow(
        `${window.location.protocol}//${window.location.host}/#/xieyi`,
        this.$t('personInfo.xinxi58'),
      );

      // this.$router.push('/xieyi');
    },
    openWindow(url, title) {
      const newWindow = window.open('about:blank', title);
      newWindow.document.title = title;
      let iframe = document.createElement('iframe');
      iframe.src = url;
      iframe.style.width = '100%';
      iframe.style.height = '100vh';
      iframe.style.margin = '0';
      iframe.style.padding = '0';
      iframe.style.overflow = 'hidden';
      iframe.style.border = 'none';
      newWindow.document.body.style.margin = '0';
      newWindow.document.body.appendChild(iframe);
    },
    // 登录
    loginTarget() {
      this.$refs.emailForm;
      this.$refs['emailForm'].validate((valid) => {
        if (valid) {
          let url, form;
          // "0验证码登录", "1邮箱登录"
          if (this.activeIndex == 0) {
            url = '/open/loginEmail';
            form = this.emailForm;
          }
          if (!this.checked) {
            return this.$message.error(this.$t('login.login1'));
          }
          if (this.passwordIscChecked) {
            localStorage.setItem('email', this.emailForm.email);
            localStorage.setItem('password', Base64.encode(this.emailForm.password));
          } else {
            localStorage.removeItem('email');
            localStorage.removeItem('password');
          }
          this.$http
            .post(url, {
              ...form,
              lang: localStorage.getItem('lang'),
            })
            .then(({ data: res }) => {
              console.log(res);
              if (res.code !== 0) {
                return this.$message.error(res.msg);
              }
              // this.$store.state.user.deptId = res.data.user.deptId
              localStorage.setItem('user_deptId', res.data.user.deptId);
              if (res.data.logoClick !== undefined && res.data.logoClick !== null) {
                localStorage.setItem('logoClick', res.data.logoClick);
              } else {
                localStorage.setItem('logoClick', '');
              }
              // this.$store.state.user.headUrl = res.data.user.headUrl
              if (res.data.user.headUrl != null && res.data.user.headUrl != '') {
                localStorage.setItem('user_headUrl', res.data.user.headUrl);
              } else {
                localStorage.setItem(
                  'user_headUrl',
                  'http://39.105.32.98/upload/20230418/8817e05ccbde439988e9aadfda3c78be.jpeg',
                );
              }
              // this.$store.state.user.id = res.data.user.id
              window.localStorage.setItem('user_id', res.data.user.userId);
              // this.$store.state.user.realName = res.data.user.realName
              window.localStorage.setItem('user_realName', res.data.user.realName);
              // this.$store.state.user.roleIdList = res.data.user.roleIdList
              // this.$store.state.user.superAdmin = res.data.user.superAdmin
              window.localStorage.setItem('user_superAdmin', res.data.user.superAdmin);

              localStorage.setItem('user_roleId', res.data.user.organizedRoleId);

              window.localStorage.setItem('user_organizedType', res.data.user.organizedType);

              window.localStorage.setItem('user_superAdmin', res.data.user.superAdmin);
              localStorage.setItem('user_owner', res.data.user.owner);
              localStorage.setItem('user_permissionsList', res.data.user.permissionsList);
              localStorage.setItem('user_adminRoleName', res.data.user.adminRoleName);
              localStorage.setItem('user_name', res.data.user.username);

              Cookies.set('token', res.data.token);
              localStorage.setItem('tg_expand', '');
              const blzEmailStr = localStorage.getItem('blz_email');
              if (blzEmailStr !== undefined && blzEmailStr !== null && blzEmailStr !== '') {
                const blzEmail = JSON.parse(blzEmailStr);
                const { path, query } = blzEmail;
                this.$router.push(
                  {
                    path,
                    query,
                  },
                  () => {
                    localStorage.removeItem('blz_email');
                  },
                );
                return;
              }

              if (res.data.user.superAdmin == 0 && !res.data.user.deptId) {
                this.$router.push('/selectionregister');
              } else {
                if (res.data.user.superAdmin == 1) {
                  this.$router.push(res.data.user.permissionsList[0]);
                } else if (res.data.user.organizedRoleId == 5) {
                  this.$router.push('/caseorder');
                } else {
                  this.$router.push('/home');
                }
              }
            })
            .catch((err) => {
              console.log('err', err);
            });
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.d {
  background-color: red;
}

.formItem_code {
  position: relative;

  .code_btn {
    position: absolute;
    right: 18px;
    top: 8px;
    color: #003e67;
    cursor: pointer;
    font-size: 14px;
    font-family: PingFang SC;
    font-weight: 400;
    line-height: 25px;
    color: #003e67;
  }
}

.login_right {
  position: relative;
}

.f-item {
  width: 346px;
  position: relative;

  .yanjin {
    width: 16px;
    cursor: pointer;
    position: absolute;
    right: 10px;
    top: -2px;
  }
}

.transform_open {
  transform: rotate(180deg);
}
.transform_close {
  transform: rotate(0deg);
}

</style>
